package com.hxfeng.authdemo.service;

import com.hxfeng.authdemo.entity.MyUser;
import com.hxfeng.authdemo.exception.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;


@Configuration
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        MyUser sysUserDetails = null;
        try {
            sysUserDetails = (MyUser) authentication.getPrincipal();
        } catch (Exception e) {
            throw new MyException(403, "权限不足");
        }

        Set<String> permissions = new HashSet<String>(); // 用户权限

//        List<TSysRes> authList = tSysResService.findResByUserId(sysUserDetails.getId());

//        for (int i = 0; i < authList.size(); i++) {
//            permissions.add(authList.get(i).getPermission());
//        }

        // 判断是否拥有权限
        if (permissions.contains(permission.toString())) {
            return true;
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
                                 Object permission) {
        return false;
    }

}
